﻿//using CleanArchitecture.Core.Configuration;
//using CleanArchitecture.Core.Interfaces;
//using CleanArchitecture.Infrastructure.Entities;
//using CleanArchitecture.Infrastructure.Entities.Business;
//using CleanArchitecture.Infrastructure.Entities.Settings;
//using CleanArchitecture.Infrastructure.Interfaces;
//using CleanArchitecture.Infrastructure.Interfaces.Media;
//using CleanArchitecture.Infrastructure.Interfaces.SystemLog;
//using Microsoft.AspNetCore.Hosting;
//using Microsoft.AspNetCore.Http;
//using SixLabors.ImageSharp;
//using SixLabors.ImageSharp.Formats;
//using SixLabors.ImageSharp.Formats.Bmp;
//using SixLabors.ImageSharp.Formats.Gif;
//using SixLabors.ImageSharp.Formats.Jpeg;
//using SixLabors.ImageSharp.Formats.Png;
//using SixLabors.ImageSharp.PixelFormats;
//using SixLabors.ImageSharp.Processing;
//using SixLabors.Primitives;
//using System;
//using System.Collections;
//using System.Collections.Generic;
//using System.IO;
//using System.Linq;
//using System.Threading;
//using System.Threading.Tasks;
//using ThumbnailSharp;
//using static SixLabors.ImageSharp.Configuration;

//namespace CleanArchitecture.Infrastructure.Services.Media.RoxyFileman
//{
//    /// <summary>
//    /// Database RoxyFileman service
//    /// </summary>
//    public class DatabaseRoxyFilemanService : FileRoxyFilemanService
//    {
//        #region Fields

//        private readonly IFileUploadService _fileuploadService;
//        private readonly IRepository<FileUpload> _pictureRepository;
//        private static IDictionary<string, int> _directories;
//        private readonly IDateTimeHelper _datetimeHelper;
//        private readonly ISystemLogService _logger;
//        #endregion

//        #region Ctor

//        public DatabaseRoxyFilemanService(IFileUploadService fileuploadService,
//            IRepository<FileUpload> pictureRepository,
//            IWebHostEnvironment hostingEnvironment,
//            IHttpContextAccessor httpContextAccessor,
//            INowaFileProvider fileProvider,
//            IWebHelper webHelper,
//            MediaSettings mediaSettings,
//            NowaConfig config,
//            IDateTimeHelper datetimeHelper,
//            ISystemLogService logger) : base(hostingEnvironment, httpContextAccessor, fileProvider, webHelper, mediaSettings, config)
//        {
//            _fileuploadService = fileuploadService;
//            _pictureRepository = pictureRepository;
//            _datetimeHelper = datetimeHelper;
//            _logger = logger;
//        }

//        #endregion

//        #region Utilities

//        /// <summary>
//        /// Get directories in the passed parent directory
//        /// </summary>
//        /// <param name="parentDirectoryPath">Path to the parent directory</param>
//        /// <param name="type">RoxyFileman take from tinymce: image,file,media</param>
//        /// <returns>Array of the paths to the directories</returns>
//        protected override ArrayList GetDirectories(string parentDirectoryPath, string type="image")
//        {
//            string[] usecase = null;
//            Type classtype = null;
//            switch(type)
//            {
//                case "file":
//                    classtype = typeof(MediaUploadUseCategory);
//                    break;
//                case "media":
//                    classtype = typeof(MediaUploadUseCategory);
//                    break;
//                case "image":
//                default:
//                    classtype = typeof(ImageUploadUseCategory);
//                    break;
//            }

//            usecase = classtype.GetProperties().Select(p => p.Name).ToArray();
//            _directories = _fileuploadService.GetVirtualDirectories(usecase);
//            CreateDirectory(parentDirectoryPath);

//            return base.GetDirectories(parentDirectoryPath);
//        }

//        /// <summary>
//        /// Gets picture from database by file
//        /// </summary>
//        /// <param name="filePath">File path</param>
//        /// <returns>Exist picture from database or null</returns>
//        protected virtual Picture GetPictureByFile(string filePath)
//        {
//            var sourceVirtualPath = _fileProvider.GetVirtualPath(_fileProvider.GetDirectoryName(filePath));
//            var fileName = _fileProvider.GetFileNameWithoutExtension(filePath);

//            var picture = _pictureService.GetPictures(sourceVirtualPath.TrimEnd('/'))
//                       .FirstOrDefault(p => fileName.Contains(p.SeoFilename));

//            return picture;
//        }

//        /// <summary>
//        /// Create the passed directory
//        /// </summary>
//        /// <param name="directoryPath">Path to the parent directory</param>
//        protected virtual void CreateDirectory(string directoryPath)
//        {
//            _fileProvider.CreateDirectory(directoryPath);
//            string abps;
//            foreach (var directory in _directories)
//            {
//                abps = GetFullPath(directory.Key.TrimStart('~'));
//                if (abps.ToLowerInvariant().Equals(directoryPath.ToLowerInvariant()))
//                    continue;
//                _fileProvider.CreateDirectory(abps);
//            }
//        }

//        /// <summary>
//        /// Get files in the passed directory
//        /// </summary>
//        /// <param name="directoryPath">Path to the files directory</param>
//        /// <param name="type">Type of the files</param>
//        /// <returns>List of paths to the files</returns>
//        protected override List<string> GetFiles(string directoryPath, string type)
//        {
//            if (type == "#")
//                type = string.Empty;

//            var files = new List<string>();

//            //store files on disk if needed
//            FlushImagesOnDisk(directoryPath);

//            foreach (var fileName in _fileProvider.GetFiles(_fileProvider.DirectoryExists(directoryPath) ? directoryPath : GetFullPath(directoryPath)))
//            {
//                if (string.IsNullOrEmpty(type) || GetFileType(_fileProvider.GetFileExtension(fileName)) == type)
//                    files.Add(fileName);
//            }

//            return files;
//        }

//        /// <summary>
//        /// Сopy the directory with the embedded files and directories
//        /// </summary>
//        /// <param name="sourcePath">Path to the source directory</param>
//        /// <param name="destinationPath">Path to the destination directory</param>
//        protected override void CopyDirectory(string sourcePath, string destinationPath)
//        {
//            var pictures = _pictureService.GetPictures($"{_fileProvider.GetVirtualPath(sourcePath).TrimEnd('/')}/");
//            var baseDestinationPathVirtualPath = _fileProvider.GetVirtualPath(destinationPath);

//            foreach (var picture in pictures)
//            {
//                var destinationPathVirtualPath =
//                    $"{baseDestinationPathVirtualPath.TrimEnd('/')}{picture.VirtualPath.Replace(_fileProvider.GetVirtualPath(sourcePath), "")}";

//                _pictureService.InsertPicture(new RoxyFilemanFormFile(picture, _pictureService.GetFileExtensionFromMimeType(picture.MimeType)), string.Empty, destinationPathVirtualPath);
//            }
//        }

//        /// <summary>
//        /// Encode the image into a byte array in accordance with the specified image format
//        /// </summary>
//        /// <typeparam name="T">Pixel data type</typeparam>
//        /// <param name="image">Image data</param>
//        /// <param name="imageFormat">Image format</param>
//        /// <param name="quality">Quality index that will be used to encode the image</param>
//        /// <returns>Image binary data</returns>
//        protected virtual byte[] EncodeImage<T>(Image<T> image, IImageFormat imageFormat, int? quality = null) where T : struct, IPixel<T>
//        {
//            using (var stream = new MemoryStream())
//            {
//                var imageEncoder = Default.ImageFormatsManager.FindEncoder(imageFormat);
//                switch (imageEncoder)
//                {
//                    case JpegEncoder jpegEncoder:
//                        jpegEncoder.Subsample = JpegSubsample.Ratio444;
//                        jpegEncoder.Quality = quality ?? _mediaSettings.DefaultImageQuality;
//                        jpegEncoder.Encode(image, stream);
//                        break;

//                    case PngEncoder pngEncoder:
//                        pngEncoder.ColorType = PngColorType.RgbWithAlpha;
//                        pngEncoder.Encode(image, stream);
//                        break;

//                    case BmpEncoder bmpEncoder:
//                        bmpEncoder.BitsPerPixel = BmpBitsPerPixel.Pixel32;
//                        bmpEncoder.Encode(image, stream);
//                        break;

//                    case GifEncoder gifEncoder:
//                        gifEncoder.Encode(image, stream);
//                        break;

//                    default:
//                        imageEncoder.Encode(image, stream);
//                        break;
//                }

//                return stream.ToArray();
//            }
//        }

//        /// <summary>
//        /// Calculates picture dimensions whilst maintaining aspect
//        /// </summary>
//        /// <param name="originalSize">The original picture size</param>
//        /// <param name="targetSize">The target picture size (longest side)</param>
//        /// <param name="resizeType">Resize type</param>
//        /// <param name="ensureSizePositive">A value indicating whether we should ensure that size values are positive</param>
//        /// <returns></returns>
//        protected virtual Size CalculateDimensions(Size originalSize, int targetSize,
//            ResizeType resizeType = ResizeType.LongestSide, bool ensureSizePositive = true)
//        {
//            float width, height;

//            switch (resizeType)
//            {
//                case ResizeType.LongestSide:
//                    if (originalSize.Height > originalSize.Width)
//                    {
//                        // portrait
//                        width = originalSize.Width * (targetSize / (float)originalSize.Height);
//                        height = targetSize;
//                    }
//                    else
//                    {
//                        // landscape or square
//                        width = targetSize;
//                        height = originalSize.Height * (targetSize / (float)originalSize.Width);
//                    }

//                    break;
//                case ResizeType.Width:
//                    width = targetSize;
//                    height = originalSize.Height * (targetSize / (float)originalSize.Width);
//                    break;
//                case ResizeType.Height:
//                    width = originalSize.Width * (targetSize / (float)originalSize.Height);
//                    height = targetSize;
//                    break;
//                default:
//                    throw new Exception("Not supported ResizeType");
//            }

//            if (!ensureSizePositive)
//                return new Size((int)Math.Round(width), (int)Math.Round(height));

//            if (width < 1)
//                width = 1;
//            if (height < 1)
//                height = 1;

//            //we invoke Math.Round to ensure that no white background is rendered - https://www.nopcommerce.com/boards/t/40616/image-resizing-bug.aspx
//            return new Size((int)Math.Round(width), (int)Math.Round(height));
//        }

//        /// <summary>
//        /// Save picture by picture virtual path
//        /// </summary>
//        /// <param name="picture">Picture instance</param>
//        /// <param name="targetSize">The target picture size (longest side)</param>
//        protected virtual void SavePictureByVirtualPath(Picture picture, int targetSize = 0)
//        {
//            if (string.IsNullOrEmpty(picture?.VirtualPath) || string.IsNullOrEmpty(picture.SeoFilename))
//                return;

//            var pictureBinary = _pictureService.LoadPictureBinary(picture);

//            if (pictureBinary == null || pictureBinary.Length == 0)
//                return;

//            var seoFileName = picture.SeoFilename;

//            var lastPart = _pictureService.GetFileExtensionFromMimeType(picture.MimeType);

//            var thumbFileName = targetSize == 0 ? $"{seoFileName}.{lastPart}" : $"{seoFileName}_{targetSize}.{lastPart}";

//            var thumbsDirectoryPath = _fileProvider.GetAbsolutePath(picture.VirtualPath.TrimStart('~'));

//            _fileProvider.CreateDirectory(thumbsDirectoryPath);
//            var thumbFilePath = _fileProvider.Combine(thumbsDirectoryPath, thumbFileName);

//            if (picture.IsNew == EntityEnumConfig.YesorNo.YES)
//            {
//                // delete old file if exist
//                _fileProvider.DeleteFile(thumbFilePath);

//                //we do not validate picture binary here to ensure that no exception ("Parameter is not valid") will be thrown
//                _pictureService.UpdatePicture(picture.Id,
//                    pictureBinary,
//                    picture.MimeType,
//                    picture.SeoFilename,
//                    picture.AltAttribute,
//                    picture.TitleAttribute,
//                    false,
//                    false);
//            }

//            //the named mutex helps to avoid creating the same files in different threads,
//            //and does not decrease performance significantly, because the code is blocked only for the specific file.
//            using (var mutex = new Mutex(false, thumbFileName))
//            {
//                if (_fileProvider.FileExists(thumbFilePath))
//                    return;

//                mutex.WaitOne();

//                //check, if the file was created, while we were waiting for the release of the mutex.
//                if (!_fileProvider.FileExists(thumbFilePath))
//                {
//                    byte[] pictureBinaryResized;
//                    if (targetSize != 0)
//                    {
//                        //resizing required
//                        using (var image = Image.Load<Rgba32>(pictureBinary, out var imageFormat))
//                        {
//                            var size = image.Size();

//                            image.Mutate(imageProcess => imageProcess.Resize(new ResizeOptions
//                            {
//                                Mode = ResizeMode.Max,
//                                Size = CalculateDimensions(size, targetSize)
//                            }));

//                            pictureBinaryResized = EncodeImage(image, imageFormat);
//                        }
//                    }
//                    else
//                    {
//                        //create a copy of pictureBinary
//                        pictureBinaryResized = pictureBinary.ToArray();
//                    }

//                    //save
//                    _fileProvider.WriteAllBytes(thumbFilePath, pictureBinaryResized);
//                }

//                mutex.ReleaseMutex();
//            }
//        }

//        /// <summary>
//        /// Flush image on disk
//        /// </summary>
//        /// <param name="picture">Image to store on disk</param>
//        /// <param name="maxWidth">Max image width</param>
//        /// <param name="maxHeight">Max image height</param>
//        protected virtual void FlushImages(Picture picture, int maxWidth, int maxHeight)
//        {
//            var image = Image.Load(picture.PictureBinary.BinaryData);

//            maxWidth = image.Width > maxWidth ? maxWidth : 0;
//            maxHeight = image.Height > maxHeight ? maxHeight : 0;

//            //save picture to folder if its not exists
//            SavePictureByVirtualPath(picture, maxWidth > maxHeight ? maxWidth : maxHeight);
//        }

//        #endregion

//        #region Methods

//        #region Configuration

//        /// <summary>
//        /// Initial service configuration
//        /// </summary>
//        public override void Configure()
//        {
//            base.Configure();
//            //DavidLee 2020/02/24 自动插图需要禁止，因为不明确图片属性无法追踪用途
//            //foreach (var filePath in _fileProvider.GetFiles(_fileProvider.GetAbsolutePath(RoxyFilemanDefaults.DefaultRootDirectory.Split('/')), topDirectoryOnly: false))
//            //{
//            //    var uniqueFileName = GetUniqueFileName(filePath, _fileProvider.GetFileNameWithoutExtension(filePath));

//            //    var picture = new Picture
//            //    {
//            //        IsNew = EntityEnumConfig.YesorNo.YES,
//            //        SeoFilename = uniqueFileName,
//            //        PictureBinary = new PictureBinary
//            //        {
//            //            BinaryData = _fileProvider.ReadAllBytes(filePath)
//            //        }
//            //    };

//            //    _pictureService.InsertPicture(
//            //        new RoxyFilemanFormFile(picture, _fileProvider.GetFileExtension(filePath)),
//            //        string.Empty, _fileProvider.GetVirtualPath(filePath));
//            //}
//        }

//        #endregion

//        #region Directories

//        /// <summary>
//        /// Move the directory
//        /// </summary>
//        /// <param name="sourcePath">Path to the source directory</param>
//        /// <param name="destinationPath">Path to the destination directory</param>
//        /// <returns>A task that represents the completion of the operation</returns>
//        public override async Task MoveDirectoryAsync(string sourcePath, string destinationPath)
//        {
//            await base.MoveDirectoryAsync(sourcePath, destinationPath);

//            var pictures = _pictureService.GetPictures($"{_fileProvider.GetVirtualPath(sourcePath).TrimEnd('/')}/");
//            var baseDestinationPathVirtualPath = _fileProvider.GetVirtualPath(destinationPath);

//            foreach (var picture in pictures)
//            {
//                var destinationPathVirtualPath =
//                    $"{baseDestinationPathVirtualPath.TrimEnd('/')}/{_fileProvider.GetDirectoryNameOnly(_fileProvider.GetAbsolutePath(sourcePath.TrimStart('~').Split('/')))}";

//                picture.VirtualPath = destinationPathVirtualPath;

//                _pictureService.UpdatePicture(picture);
//            }
//        }

//        /// <summary>
//        /// Rename the directory
//        /// </summary>
//        /// <param name="sourcePath">Path to the source directory</param>
//        /// <param name="newName">New name of the directory</param>
//        /// <returns>A task that represents the completion of the operation</returns>
//        public override async Task RenameDirectoryAsync(string sourcePath, string newName)
//        {
//            var sourceVirtualPath = _fileProvider.GetVirtualPath(sourcePath).TrimEnd('/');
//            var pictures = _pictureService.GetPictures($"{sourceVirtualPath}/");

//            var destinationPath =
//                $"{_fileProvider.GetVirtualPath(_fileProvider.GetParentDirectory(_fileProvider.GetAbsolutePath(sourcePath.Split('/')))).TrimEnd('/')}/{newName}";

//            foreach (var picture in pictures)
//            {
//                picture.VirtualPath = destinationPath;

//                _pictureService.UpdatePicture(picture);
//            }

//            await base.RenameDirectoryAsync(sourcePath, newName);
//        }

//        #endregion

//        #region Files
//        /// <summary>
//        /// DavidLee 2019/12/12 由于包含服务器文件存储，数据库信息存储，还有云存储，
//        /// 需要更改逻辑以数据获取数据为准
//        /// </summary>
//        /// <param name="type">TinyMcd :file_picker_callback : file, image, media</param>
//        /// <returns>A task that represents the completion of the operation</returns>
//        public override async Task GetDirectoriesAsync(string type)
//        {
//            var rootDirectoryPath = GetFullPath(GetVirtualPath(null));

//            if (!_fileProvider.DirectoryExists(rootDirectoryPath))
//                throw new Exception("Invalid files root directory. Check your configuration.");
            
//            var allDirectories = GetDirectories(rootDirectoryPath, type);
//            allDirectories.Insert(0, rootDirectoryPath);

//            var localPath = GetFullPath(null);
//            await GetHttpContext().Response.WriteAsync("[");
//            string directoryPath;
//            string responsePath;
//            int filesCount;
//            int dirCount;
//            for (var i = 0; i < allDirectories.Count; i++)
//            {
//                directoryPath = (string)allDirectories[i];
//                responsePath = directoryPath.Replace(localPath, string.Empty).Replace("\\", "/");
//                _directories.TryGetValue("~" + responsePath, out filesCount);
//                dirCount = allDirectories.ToArray()
//                            .Where(d => d.ToString().StartsWith(directoryPath))
//                            .ToList().Count;
//                //store files on disk if needed
//                FlushImagesOnDisk(directoryPath);
//                await GetHttpContext().Response.WriteAsync($"{{\"p\":\"/{responsePath.TrimStart('/')}\",\"f\":\"{filesCount}\",\"d\":\"{dirCount - 1}\"}}");
//                if (i < allDirectories.Count - 1)
//                    await GetHttpContext().Response.WriteAsync(",");
//            }

//            await GetHttpContext().Response.WriteAsync("]");
//        }

//        /// <summary>
//        /// DavidLee 2019/12/12 修改Roxy_Fileman图片上传获取图片逻辑
//        /// 新增云存储功能图片有可能保存在本地服务器有可能上云，一切以数据库数据为准
//        /// </summary>
//        /// <param name="directoryPath">Path to the files directory</param>
//        /// <param name="type">Type of the files</param>
//        /// <returns>A task that represents the completion of the operation</returns>
//        public override async Task GetFilesAsync(string directoryPath, string type)
//        {
//            if (!type.ToLowerInvariant().Equals("image"))
//            {
//                await base.GetFilesAsync(directoryPath, type);
//                return;
//            }
//            directoryPath = GetVirtualPath(directoryPath);
//            var files = _pictureService.GetPictures(directoryPath);
//            await GetHttpContext().Response.WriteAsync("[");
//            int width = 0;
//            int height = 0;
//            string imageUrl;
//            for (int i = 0; i < files.Count; i++)
//            {
//                //if (image.StoreType == EntityEnumConfig.FileStoreType.LocalStorage)
//                imageUrl = directoryPath.TrimEnd('/') + "/" + files[i].SeoFilename + _pictureService.GetImageExtensionByMimeType(files[i].MimeType);
//                if (files[i].StoreType == EntityEnumConfig.FileStoreType.QiniuCloud) //Qiniu Cloud
//                    imageUrl = nowaConfig.QiniuDomain.TrimEnd('/') + "/" + imageUrl.TrimStart('/');
//                byte[] pictureBinary = _pictureService.LoadPictureBinary(files[i]);
//                using (var image = Image.Load(pictureBinary))
//                {
//                    width = image.Width;
//                    height = image.Height;
//                    image.Dispose();
//                }
//                if (files[i].StoreType == EntityEnumConfig.FileStoreType.LocalStorage && files[i].IsNew == EntityEnumConfig.YesorNo.YES)
//                    FlushImages(files[i], width, height);
//                await GetHttpContext().Response.WriteAsync($"{{\"p\":\"{imageUrl}\",\"t\":\"{Math.Ceiling(GetTimestamp(_datetimeHelper.ConvertToUserTime(files[i].CreatedOnTimeUtc, DateTimeKind.Local)))}\",\"s\":\"{pictureBinary.Length}\",\"w\":\"{width}\",\"h\":\"{height}\"}}");

//                if (i < files.Count - 1)
//                    await GetHttpContext().Response.WriteAsync(",");
//            }

//            await GetHttpContext().Response.WriteAsync("]");
//        }

//        /// <summary>
//        /// Create the thumbnail of the image and write it to the response
//        /// </summary>
//        /// <param name="path">Path to the image</param>
//        public override Stream CreateImageThumbnail(string path, int width, int height)
//        {
//            if (!(nowaConfig.QiniuCloudStorageEnabled && path.StartsWith(nowaConfig.QiniuDomain)))
//                return base.CreateImageThumbnail(path, width, height);

//            if (width == 0 || height == 0)
//            {
//                int.TryParse(GetSetting("PREVIEW_THUMB_WIDTH"), out width);
//                int.TryParse(GetSetting("PREVIEW_THUMB_HEIGHT"), out height);
//            }

//            string defaultImgPath = GetFullPath("/images/filenotfound.jpg");
//            Stream imageStream = _pictureService.GetCloudImageStream(path, defaultImgPath);

//            using (var image = new System.Drawing.Bitmap(System.Drawing.Image.FromStream(imageStream)))
//            {
//                var imgRatio = image.Width / (double)image.Height;

//                if (height == 0)
//                    height = Convert.ToInt32(Math.Floor(width / imgRatio));

//                if (width > image.Width)
//                    width = image.Width - 1; //using ThumbnailSharp From github below
//                if (height > image.Height)
//                    height = image.Height - 1;
//                //https://github.com/mirzaevolution/ThumbnailSharp
//                //Attention: ThumbnailSharp要求要剪切略缩图尺寸要比原图尺寸小，否则会报异常：thumbnail size must less then image size
//                //           这就是为什么 image.Width - 1的原因
//                Stream resultStream = new ThumbnailCreator().CreateThumbnailStream(
//                    thumbnailSize: (uint)width,
//                    imageStream: imageStream,
//                    imageFormat: Format.Png
//                );
//                imageStream.Close();
//                image.Dispose();
//                return resultStream;
//            }
//        }

//        /// <summary>
//        /// Copy the file
//        /// </summary>
//        /// <param name="sourcePath">Path to the source file</param>
//        /// <param name="destinationPath">Path to the destination file</param>
//        /// <returns>A task that represents the completion of the operation</returns>
//        public override async Task CopyFileAsync(string sourcePath, string destinationPath)
//        {
//            var filePath = _fileProvider.GetAbsolutePath(sourcePath.Split('/'));
//            var picture = GetPictureByFile(filePath);

//            if (picture == null)
//                throw new Exception(GetLanguageResource("E_CopyFile"));

//            _pictureService.InsertPicture(
//                new RoxyFilemanFormFile(picture, _fileProvider.GetFileExtension(filePath)),
//                string.Empty, _fileProvider.GetVirtualPath(destinationPath));

//            await GetHttpContext().Response.WriteAsync(GetSuccessResponse());
//        }

//        /// <summary>
//        /// Delete the file
//        /// </summary>
//        /// <param name="sourcePath">Path to the file</param>
//        /// <returns>A task that represents the completion of the operation</returns>
//        public override async Task DeleteFileAsync(string sourcePath)
//        {
//            var filePath = _fileProvider.GetAbsolutePath(sourcePath.Split('/'));
//            var picture = GetPictureByFile(filePath);

//            if (picture == null)
//                throw new Exception(GetLanguageResource("E_DeletеFile"));

//            _pictureService.DeletePicture(picture);

//            await base.DeleteFileAsync(sourcePath);
//        }

//        /// <summary>
//        /// Move the file
//        /// </summary>
//        /// <param name="sourcePath">Path to the source file</param>
//        /// <param name="destinationPath">Path to the destination file</param>
//        /// <returns>A task that represents the completion of the operation</returns>
//        public override async Task MoveFileAsync(string sourcePath, string destinationPath)
//        {
//            await base.MoveFileAsync(sourcePath, destinationPath);

//            var filePath = _fileProvider.GetAbsolutePath(sourcePath.Split('/'));
//            var picture = GetPictureByFile(filePath);

//            if (picture == null)
//                throw new Exception(GetLanguageResource("E_MoveFile"));

//            picture.VirtualPath = _fileProvider.GetVirtualPath(_fileProvider.GetVirtualPath(_fileProvider.GetDirectoryName(destinationPath)));
//            _pictureService.UpdatePicture(picture);
//        }

//        /// <summary>
//        /// Rename the file
//        /// </summary>
//        /// <param name="sourcePath">Path to the source file</param>
//        /// <param name="newName">New name of the file</param>
//        /// <returns>A task that represents the completion of the operation</returns>
//        public override async Task RenameFileAsync(string sourcePath, string newName)
//        {
//            var filePath = _fileProvider.GetAbsolutePath(_fileProvider.GetVirtualPath(sourcePath));
//            var picture = GetPictureByFile(filePath);

//            if (picture == null)
//                throw new Exception(GetLanguageResource("E_RenameFile"));

//            picture.SeoFilename = _fileProvider.GetFileNameWithoutExtension(newName);

//            _pictureService.UpdatePicture(picture);

//            await base.DeleteFileAsync(sourcePath);
//        }

//        /// <summary>
//        /// Get the unique name of the file (add -copy-(N) to the file name if there is already a file with that name in the directory)
//        /// DavidLee 2019/12/12 对上传七牛云的文件进行兼容，并对实际服务器端保存的文件如出现重名进行文件命名改造
//        /// </summary>
//        /// <param name="directoryPath">Path to the file directory</param>
//        /// <param name="fileName">Original file name</param>
//        /// <returns>Unique name of the file</returns>
//        protected override string GetUniqueFileName(string directoryPath, string fileName)
//        {
//            string fileExt = _fileProvider.GetFileExtension(fileName);
//            string uniqueFileName = _pictureService.GetPictureSeName(fileName.Substring(0, fileName.LastIndexOf('.')));
//            uniqueFileName = DateTime.Now.ToString("yyyyMMddHHmmssffffff") + uniqueFileName + fileExt;//重命名文件加上时间戳
//            return uniqueFileName;
//        }
//        /// <summary>
//        /// Upload files to a directory on passed path
//        /// </summary>
//        /// <param name="directoryPath">Path to directory to upload files</param>
//        /// <returns>A task that represents the completion of the operation</returns>
//        public override async Task UploadFilesAsync(string directoryPath)
//        {
//            var result = GetSuccessResponse();
//            var hasErrors = false;
//            try
//            {
//                //DavidLee 2019/12/12 改造结合七牛云及虚拟目录实现客户端文件
//                //                    保存数据库并直传七牛云存储，不在服务器端保存
//                string virtualPath = GetVirtualPath(directoryPath);
//                var fullPath = GetFullPath(virtualPath);
//                foreach (var formFile in GetHttpContext().Request.Form.Files)
//                {
//                    var fileName = formFile.FileName;
//                    long fileSize = formFile.Length;
//                    if (IsFileOverSize(fileSize))
//                    {
//                        hasErrors = true;
//                        result = GetErrorResponse(GetLanguageResource("E_UploadNoFiles"));
//                        goto UploadResponse;
//                    }
//                    if (CanHandleFile(fileName))
//                    {
//                        var uniqueFileName = GetUniqueFileName(fullPath, _fileProvider.GetFileName(fileName));
//                        var destinationFile = _fileProvider.Combine(fullPath, uniqueFileName);

//                        if (GetFileType(new FileInfo(uniqueFileName).Extension) != "image")
//                        {
//                            using (var stream = new FileStream(destinationFile, FileMode.OpenOrCreate))
//                            {
//                                formFile.CopyTo(stream);
//                            }
//                        }
//                        else
//                        {
//                            var img = _pictureService.InsertPicture(formFile, uniqueFileName, GetVirtualPath(directoryPath));
//                            if (nowaConfig.QiniuCloudStorageEnabled)
//                                _pictureService.UploadImg2Cloud(img);
//                        }
//                    }
//                    else
//                    {
//                        hasErrors = true;
//                        result = GetErrorResponse(GetLanguageResource("E_UploadNotAll"));
//                    }
//                }
//            }
//            catch (Exception ex)
//            {
//                result = GetErrorResponse(ex.Message);
//            }
//            UploadResponse:
//            if (IsAjaxRequest())
//            {
//                if (hasErrors)
//                    result = GetErrorResponse(GetLanguageResource("E_UploadNotAll"));

//                await GetHttpContext().Response.WriteAsync(result);
//            }
//            else
//                await GetHttpContext().Response.WriteAsync($"<script>parent.fileUploaded({result});</script>");
//        }

//        #endregion

//        #region Images

//        /// <summary>
//        /// Flush all images on disk
//        /// </summary>
//        /// <param name="removeOriginal">Specifies whether to delete original images</param>
//        public override void FlushAllImagesOnDisk(bool removeOriginal = true)
//        {
//            base.FlushAllImagesOnDisk(removeOriginal);

//            var pageIndex = 0;
//            const int pageSize = 400;
//            int.TryParse(GetSetting("MAX_IMAGE_WIDTH"), out var width);
//            int.TryParse(GetSetting("MAX_IMAGE_HEIGHT"), out var height);

//            try
//            {
//                while (true)
//                {
//                    var pictures = _pictureService.GetPictures($"~{RoxyFilemanDefaults.DefaultRootDirectory}/",
//                        pageIndex, pageSize);
//                    pageIndex++;

//                    //all pictures flushed?
//                    if (!pictures.Any())
//                        break;

//                    foreach (var picture in pictures)
//                    {
//                        FlushImages(picture, width, height);
//                    }

//                    if (removeOriginal)
//                        _pictureRepository.Delete(pictures);
//                }
//            }
//            catch
//            {
//                // ignored
//            }
//        }

//        /// <summary>
//        /// Flush images on disk
//        /// </summary>
//        /// <param name="directoryPath">Directory path to flush images</param>
//        public override void FlushImagesOnDisk(string directoryPath)
//        {
//            base.FlushImagesOnDisk(directoryPath);

//            foreach (var picture in _pictureService.GetPictures(_fileProvider.GetVirtualPath(directoryPath)))
//            {
//                //DavidLee 2019/12/12 对于Qiniu云存储文件不在本地保存，则不用保存服务器目录
//                if (picture.StoreType == EntityEnumConfig.FileStoreType.QiniuCloud)
//                    continue;
//                int.TryParse(GetSetting("MAX_IMAGE_WIDTH"), out var width);
//                int.TryParse(GetSetting("MAX_IMAGE_HEIGHT"), out var height);

//                FlushImages(picture, width, height);
//            }
//        }

//        #endregion

//        #endregion
//    }
//}